package com.extension.company.model.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.extension.company.admin.R;
import com.extension.company.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;


/**
 * 省市区数据库，如何导入到app的data目录下
 * 数据库的
 */
public class AreaDataBase {
	private final int BUFFER_SIZE = 1024;
	public static final String DB_NAME = "address.db"; //保存的数据库文件名
	//    public static final String DB_PATH
//            = Environment.getExternalStorageDirectory().getPath() + "/Download";  // /storage/emulated/0/Download/)
	private SQLiteDatabase database;
	private Context context;

	public AreaDataBase(Context context) {
		this.context = context;
	}

	/**
	 * 打开数据库
	 *
	 * @return
	 */
	public SQLiteDatabase openDatabase() {
//		System.out.println(DB_PATH + "/" + DB_NAME);  ///storage/emulated/0/Download/extensioncompany.db
		String DB_PATH = File.separator + "data" + Environment.getDataDirectory().getAbsoluteFile() + File.separator +
				MyApplication.getContext().getPackageName() + File.separator + "databases";
		this.database = openDatabase(DB_PATH + "/" + DB_NAME);
		return database;
	}

	/**
	 * @param dbfile 数据库的存放路径
	 * @return 数据库对象
	 */
	private SQLiteDatabase openDatabase(String dbfile) {
		try {
			File file = new File(dbfile);
			if (!file.exists()) {
				//判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
				// area 存储的是所有的地级市
				InputStream is = this.context.getResources().openRawResource(R.raw.area); //欲导入的数据库
				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) != -1) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
			return db;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 关闭数据库
	 */
	public void closeDatabase() {
		this.database.close();
	}
}





